<template>
    <el-card shadow="never">
        <template #header>
            <div class="card-header">
                <span>商品管理</span>
            </div>
        </template>
        <el-row :gutter="12">
            <el-col :span="5">
                <el-input placeholder="请输入商品名" v-model="searchContent"></el-input>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" size="small" @click="goodsSearch">搜索</el-button>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" size="small" @click="addGoodsInfo()">添加</el-button>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column width="60" label="序号">
                <template #default="scope">
                    <span>{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="商品名称" width="auto">
                <template #default="scope">
                    <el-popover effect="light" trigger="hover" placement="right">
                        <template #default>
                            <p>ID：{{ scope.row.id }}</p>
                            <p>商品名称: {{ scope.row.name }}</p>
                            <p>介绍: {{ scope.row.intro }}</p>
                            <p>上架时间: {{ scope.row.pubdate }}</p>
                            <p>指数: {{ scope.row.star }}</p>
                        </template>
                        <template #reference>
                            <div class="name-wrapper">
                                <el-tag size="medium">{{ scope.row.name }}</el-tag>
                            </div>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="图片" width="80">
                <template #default="scope">
                    <el-popover effect="light" trigger="hover" placement="right">
                        <template #default>
                            <img
                                :src="imagesURL + scope.row.picture"
                                style="width:200px; height:200px;"
                            />
                        </template>
                        <template #reference>
                            <div class="name-wrapper">
                                <img
                                    :src="imagesURL + scope.row.picture"
                                    style="width:40px; height:40px;"
                                />
                            </div>
                        </template>
                    </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="价格" width="80">
                <template #default="scope">
                    <span style="margin-left: 10px">{{ scope.row.price }}</span>
                </template>
            </el-table-column>
            <el-table-column label="类型" width="80">
                <template #default="scope">
                    <span style="margin-left: 10px">{{ scope.row.typeName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="180">
                <template #default="scope">
                    <span style="margin-left: 10px; color:green" v-if="scope.row.flag == 1">已上架</span>
                    <span style="margin-left: 10px; color:gray" v-if="scope.row.flag == 0">已下架</span>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        @click="goodsUpdate(scope.$index, scope.row)"
                    >修改</el-button>
                    <el-button
                        size="mini"
                        type="success"
                        v-if="scope.row.flag == 0"
                        @click="goodsUp(scope.row.id, scope.row.flag)"
                    >上架</el-button>
                    <el-button
                        size="mini"
                        type="warning"
                        v-if="scope.row.flag == 1"
                        @click="goodsDown(scope.row.id, scope.row.flag)"
                    >下架</el-button>
                    <el-button size="mini" type="danger" @click="goodsDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="changePage"
        ></el-pagination>
    </el-card>
    <addGoods 
        :centerDialogVisible="centerDialogVisible"
        @onCloseDialog="closeDialogVisible"
    ></addGoods>
    <updateGoods 
        v-if='updateDialogVisible===true' 
        :updateDialogVisible="updateDialogVisible" 
        :goodsId="gId"
        @onCloseUpdateDialog="closeUpdateDialogVisible"
    ></updateGoods>
</template>

<script>
import { onMounted, reactive, toRefs, ref } from "vue";
import axios from 'axios'
import addGoods from './addGoods.vue'
import updateGoods from './updateGoods.vue'
import { ElMessageBox, ElNotification } from "element-plus";

// 读取页面数据
function loadData(state) {
    const params = {
        pageCurrent: state.currentPage,
        pageSize: state.pageSize,
        search: state.searchContent,
    }
    axios({
        url: '/selectGoodsOffset',
        method: 'get',
        params: params,
    }).then(res => {
        // console.log(res.data.data)
        state.tableData = res.data.data.list;
        state.total = res.data.data.total // 总的记录数
    });
}

//修改商品
function useGoodsUpdate(state) {
    const goodsUpdate = (index, row) => {
        state.updateDialogVisible = true;
        state.gId = row.id;
    }
    return {
        goodsUpdate,
    }
}

// 删除商品
function useGoodsDelete(state) {
    const goodsDelete = (id) => {
        // console.log('index=',index)
        console.log('id=', id)
        ElMessageBox.confirm("是否确认删除该商品？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            callback: (action) => {
                if (action == 'confirm') {
                    axios({
                        url: '/goodsDeleteById',
                        method: 'get',
                        params: {
                            id: id
                        }
                    }).then(res => {
                        console.log(res)
                        if (res.data.code == 200) {
                            ElNotification({
                                title: "成功",
                                message: "删除成功",
                                type: "success",
                                duration: 2000,
                            });
                            loadData(state)
                        } else {
                            ElNotification({
                                title: "失败",
                                message: "删除失败",
                                type: "error",
                                duration: 2000,
                            });
                        }
                    });
                }
            },
        });
    }
    return {
        goodsDelete
    }
}

// 搜索商品
function useGoodsSearch(state) {
    const goodsSearch = () => {
        state.currentPage = 1;
        const params = {
            pageCurrent: state.currentPage,
            pageSize: state.pageSize,
            name: state.searchContent,
            // pubdate: state.pickerDate,
        }
        axios({
            url: '/selectByNameAndPubOffset',
            method: 'get',
            params: params
        }).then(res => {
            // console.log(res.data)
            if (res.data.code == 200) {
                state.tableData = res.data.data.list
                state.total = res.data.data.total
            } else {
                state.tableData = [];
                ElNotification({
                    title: "失败",
                    message: "查无此信息",
                    type: "error",
                    duration: 2000,
                });
            }
        });
    };
    return {
        goodsSearch,
    }
}

// 商品上下架
function useGoodsUp(state) {
    const goodsUp = (id, flag) => {
        const params = {
            id: id,
            flag: flag,
        }
        axios({
            url: '/goodsAltFlagByFlagAndId',
            method: 'get',
            params: params
        }).then(res => {
            // console.log(res.data)
            loadData(state)
        })
    }
    return {
        goodsUp,
    }
}
function useGoodsDown(state) {
    const goodsDown = (id, flag) => {
        const params = {
            id: id,
            flag: flag,
        }
        axios({
            url: '/goodsAltFlagByFlagAndId',
            method: 'get',
            params: params
        }).then(res => {
            // console.log(res.data)
            loadData(state)
        })
    }
    return {
        goodsDown,
    }
}

export default {
    components: {
        addGoods, // 注册组件
        updateGoods,
    },
    setup() {
        const state = reactive({
            tableData: [],
            centerDialogVisible: false,
            updateDialogVisible: false, // 控制修改窗口显示与隐藏
            total: 0,
            currentPage: 1,     // 当前页码
            pageSize: 6,
            searchContent: "",  // 搜索条件姓名
            pickerDate: "",         //搜索条件时间
            gId: 0, //要修改的商品id
        });
        const imagesURL = import.meta.env.VITE_APP_URL + "/images/";

        onMounted(() => {
            loadData(state);
        });
        // 分页-页面切换的时候执行该方法
        const changePage = (val) => {
            state.currentPage = val;
            loadData(state);
            document.body.scrollTop = 0
            document.documentElement.scrollTop = 0
        };
        const addGoodsInfo = () => {
            state.centerDialogVisible = true;
        };
        const closeDialogVisible = (visible, data) => {
            state.centerDialogVisible = visible;
            // console.log(data)
            //返回成功的data，重新添加到数据中，令自动读取
            if (data !== undefined) {
                // state.tableData.push(data);
                loadData(state);
            }
        };
        const closeUpdateDialogVisible=(visible, data)=>{
            state.updateDialogVisible = visible;
            if(data !==undefined){
                loadData(state);
            }
        };

        return {
            ...toRefs(state), //...解构结构后不是响应式对象。toRefs数据转换成响应式对象
            imagesURL,
            addGoodsInfo,
            closeDialogVisible,
            ...useGoodsSearch(state),
            ...useGoodsDelete(state),
            changePage,
            ...useGoodsUp(state),
            ...useGoodsDown(state),
            ...useGoodsUpdate(state),
            closeUpdateDialogVisible,
        };
    },
    methods: {
        // 序号-自动递增
        indexMethod(index) {
            return index = index + 1;
        }
    },
};
</script>
<style>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
</style>